package com.ruoyi.system.service.impl;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.system.domain.Email;
import com.ruoyi.system.service.EmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.Date;

@Service
public class EmailServiceImpl implements EmailService {

    @Autowired(required = false)
    private JavaMailSender sender;

    @Value("${spring.mail.username}")
    private String username;
    @Override
    @Async
    public void sendSimpleEmail(String emailTheme,String emailContent,String email) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setSubject(emailTheme);
        message.setText(emailContent);
        message.setTo(email);
        message.setFrom(username);
        try {
            // 发送邮件;
            sender.send(message);
            System.out.println("纯文本邮件发送成功");
        } catch (MailException e) {
            System.out.println("纯文本邮件发送失败 " + e.getMessage());
            e.printStackTrace();
        }
    }
    @Override
    public void receiveMail(Email email) {
        try {
            MimeMessageHelper message = new MimeMessageHelper(sender.createMimeMessage(),true);
            message.setSubject(email.getSubject());
            message.setText(email.getText());
            message.setTo(email.getTo());
            message.setFrom(email.getFrom());
            message.setSentDate(new Date());
            if (email.getFilePathName()!=null){
                String url = RuoYiConfig.getUploadPath() + email.getFilePathName();
                String substring = url.substring(0, 11);
                String substring1 = url.substring(26);
                String url1 = substring+substring1;
                message.addAttachment(email.getFilePathName(), new File(url1));
            }
            sender.send(message.getMimeMessage());
            System.out.println("邮件发送成功");
        } catch (Exception e) {
            System.out.println("邮件发送失败 " + e.getMessage());
            e.printStackTrace();
        }
    }
}
